//@ts-nocheck
import React, { useState, useRef, useImperativeHandle} from 'react';
import ReactDOM from 'react-dom';

function Child(props: any, ref: any){
  const refObject1 = useRef();
  const refObject2 = useRef();
  //选择性的暴露属性方法
  useImperativeHandle(ref, () => ({
    //这里定义的就是refObject.current.在外部组件中能点出来的值
    focus() {
      //@ts-ignore
      refObject1.current.focus()
    }
    , setVal(val: any) {
      //@ts-ignore
      refObject2.current.value = val
    }
  }),[]/*←一般为空数组即可,不需要重复渲染调用*/);
  return (
    <div>
      <input type="text" ref={refObject1}/>
      <input type="text" ref={refObject2}/>
    </div>
  )
}

const ForwardChild = React.forwardRef(Child);
function Parent(){
  const [number, setNumber] = useState(0);
  const refObject = useRef();

  function getFocus(){
    console.log('父组件拿到的ref是:',refObject);
    //@ts-ignore
    refObject.current.focus();
    //@ts-ignore
    //refObject.current.value = 'xx' //并不会有效果
  }

  function setVal(val: any){
    //@ts-ignore
    refObject.current.setVal(val)
  }
  return (
    <div>
      <ForwardChild ref={refObject}/>
      <button onClick={getFocus}>获得焦点</button>
      <button onClick={()=>setVal(Date.now())}>设置值</button>
      <button onClick={()=>setNumber(x=>x+1)}>+</button>
    </div>
  )
}

ReactDOM.render(<Parent/>, document.getElementById('root'));
